package com.hezy.base.application;

import android.app.Application;
import android.content.res.Configuration;

import com.bumptech.glide.Glide;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public abstract class BaseApplication extends Application {

    private List<IComponent> components = new ArrayList<>();

    public abstract String[] getComponentNames();

    @Override
    public void onCreate() {
        super.onCreate();
        initComponents();
    }

    private void initComponents() {
        String[] componentNames = getComponentNames();
        for (String item : componentNames) {
            try {
                Class<?> clazz = Class.forName(item);
                Constructor<?> constructor = clazz.getConstructor(Application.class);
                Object instance = constructor.newInstance(this);
                if (instance instanceof IComponent) {
                    IComponent iComponent = (IComponent) instance;
                    components.add(iComponent);
                    iComponent.onCreate();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        Collections.sort(components, new Comparator<IComponent>() {
            @Override
            public int compare(IComponent o1, IComponent o2) {
                return o1.getPriority() - o2.getPriority();
            }
        });
    }


    @Override
    public void onLowMemory() {
        super.onLowMemory();
        for (IComponent item : components) {
            item.onLowMemory();
        }
    }

    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
        for (IComponent item : components) {
            item.onTrimMemory(level);
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        for (IComponent item : components) {
            item.onConfigurationChanged(newConfig);
        }
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        for (IComponent item : components) {
            item.onTerminate();
        }
    }
}
